/**
 * SubAgentManager - Enhanced Sub-Agent Management Interface
 * 
 * Features:
 * - List all sub-agents (builtin + custom)
 * - Search and filter by category
 * - View sub-agent details
 * - Create, edit, delete custom sub-agents
 * - Import/export configurations
 */

import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Plus,
  Search,
  Filter,
  Upload,
  Edit,
  Trash2,
  Eye,
  Sparkles,
  Library
} from 'lucide-react';
import { SubAgentCreator } from './SubAgentCreator';
import { SubAgentEditor } from './SubAgentEditor';
import { SubAgentTemplates } from './SubAgentTemplates';
import { AISubAgentGenerator } from './AISubAgentGenerator';
import { SubAgentImportExport } from './SubAgentImportExport';

// Sub-Agent Interface
interface SubAgent {
  id: string;
  name: string;
  description: string;
  prompt: string;
  tools?: string[];
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
  skillIds?: string[];
  category?: string;
  tags?: string[];
  isBuiltin?: boolean;
}

// Stats Interface
interface SubAgentStats {
  total: number;
  builtin: number;
  custom: number;
  byCategory: Record<string, number>;
}

export function SubAgentManager() {
  const [subAgents, setSubAgents] = useState<SubAgent[]>([]);
  const [stats, setStats] = useState<SubAgentStats | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [showCreator, setShowCreator] = useState(false);
  const [showTemplates, setShowTemplates] = useState(false);
  const [showAIGenerator, setShowAIGenerator] = useState(false);
  const [showImportExport, setShowImportExport] = useState(false);
  const [editingAgent, setEditingAgent] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');

  // Fetch sub-agents from API
  useEffect(() => {
    fetchSubAgents();
  }, []);

  const fetchSubAgents = async () => {
    try {
      const response = await fetch('http://localhost:3000/api/subagents');
      const data = await response.json();
      if (data.success) {
        setSubAgents(data.data.subagents);
        setStats(data.data.stats);
      }
    } catch (error) {
      console.error('Failed to fetch sub-agents:', error);
    }
  };

  const handleCreateSubAgent = async (config: SubAgent) => {
    try {
      const response = await fetch('http://localhost:3000/api/subagents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config),
      });
      const data = await response.json();
      if (data.success) {
        await fetchSubAgents();
        setShowCreator(false);
      }
    } catch (error) {
      console.error('Failed to create sub-agent:', error);
    }
  };

  const handleDeleteSubAgent = async (id: string) => {
    if (!confirm('确定要删除这个 sub-agent 吗？')) return;
    
    try {
      const response = await fetch(`http://localhost:3000/api/subagents/${id}`, {
        method: 'DELETE',
      });
      const data = await response.json();
      if (data.success) {
        await fetchSubAgents();
      }
    } catch (error) {
      console.error('Failed to delete sub-agent:', error);
    }
  };

  // Filter sub-agents
  const filteredAgents = subAgents.filter((agent) => {
    const matchesSearch = agent.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         agent.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || agent.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  // Get unique categories
  const categories = ['all', ...new Set(subAgents.map(a => a.category).filter(Boolean))];

  // Handle template apply
  const handleApplyTemplate = (template: any) => {
    // Convert template to SubAgentConfig format
    const config = {
      id: template.id,
      name: template.name,
      description: template.description,
      prompt: template.prompt,
      tools: template.tools,
      model: template.model,
      category: template.category,
      tags: template.tags,
    };
    handleCreateSubAgent(config);
  };

  // Handle edit save
  const handleEditSave = async (config: SubAgent) => {
    try {
      const response = await fetch(`http://localhost:3000/api/subagents/${config.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config),
      });
      const data = await response.json();
      if (data.success) {
        await fetchSubAgents();
        setEditingAgent(null);
      }
    } catch (error) {
      console.error('Failed to update sub-agent:', error);
    }
  };

  if (showCreator) {
    return (
      <SubAgentCreator
        onSave={handleCreateSubAgent}
        onCancel={() => setShowCreator(false)}
      />
    );
  }

  if (showTemplates) {
    return (
      <SubAgentTemplates
        onApply={handleApplyTemplate}
        onClose={() => setShowTemplates(false)}
      />
    );
  }

  if (editingAgent) {
    return (
      <SubAgentEditor
        agentId={editingAgent}
        onSave={handleEditSave}
        onClose={() => setEditingAgent(null)}
      />
    );
  }

  if (showAIGenerator) {
    return (
      <AISubAgentGenerator
        onGenerate={handleCreateSubAgent}
        onCancel={() => setShowAIGenerator(false)}
      />
    );
  }

  if (showImportExport) {
    return (
      <SubAgentImportExport
        onClose={() => {
          setShowImportExport(false);
          fetchSubAgents(); // Refresh list after import
        }}
      />
    );
  }

  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h1 className="text-3xl font-bold">Sub-Agents 管理</h1>
            <p className="text-muted-foreground mt-1">
              管理和配置 AI sub-agents
            </p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => setShowTemplates(true)}>
              <Library className="w-4 h-4 mr-2" />
              浏览模板
            </Button>
            <Button variant="outline" onClick={() => setShowImportExport(true)}>
              <Upload className="w-4 h-4 mr-2" />
              导入/导出
            </Button>
            <Button variant="outline" onClick={() => setShowAIGenerator(true)}>
              <Sparkles className="w-4 h-4 mr-2" />
              AI 生成
            </Button>
            <Button onClick={() => setShowCreator(true)}>
              <Plus className="w-4 h-4 mr-2" />
              创建 Sub-Agent
            </Button>
          </div>
        </div>

        {/* Stats */}
        {stats && (
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>总计</CardDescription>
                <CardTitle className="text-3xl">{stats.total}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>内置</CardDescription>
                <CardTitle className="text-3xl">{stats.builtin}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>自定义</CardDescription>
                <CardTitle className="text-3xl">{stats.custom}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>分类</CardDescription>
                <CardTitle className="text-3xl">{Object.keys(stats.byCategory).length}</CardTitle>
              </CardHeader>
            </Card>
          </div>
        )}

        {/* Search and Filter */}
        <div className="flex gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索 sub-agents..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>
          <select
            className="flex h-9 rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"
            value={selectedCategory}
            onChange={(e) => setSelectedCategory(e.target.value)}
          >
            {categories.map((cat) => (
              <option key={cat} value={cat}>
                {cat === 'all' ? '所有分类' : cat}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Sub-Agents Grid */}
      <div className={viewMode === 'grid' ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4' : 'space-y-4'}>
        {filteredAgents.map((agent) => (
          <Card key={agent.id} className="hover:shadow-lg transition-shadow">
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <CardTitle className="text-lg flex items-center gap-2">
                    {agent.name}
                    {agent.isBuiltin && (
                      <Badge variant="secondary" className="text-xs">内置</Badge>
                    )}
                  </CardTitle>
                  <CardDescription className="mt-1 line-clamp-2">
                    {agent.description}
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <Badge variant="outline">{agent.category}</Badge>
                  <Badge variant="outline" className="capitalize">{agent.model || 'inherit'}</Badge>
                </div>
                
                {agent.tags && agent.tags.length > 0 && (
                  <div className="flex flex-wrap gap-1">
                    {agent.tags.slice(0, 3).map((tag) => (
                      <Badge key={tag} variant="secondary" className="text-xs">
                        {tag}
                      </Badge>
                    ))}
                    {agent.tags.length > 3 && (
                      <Badge variant="secondary" className="text-xs">
                        +{agent.tags.length - 3}
                      </Badge>
                    )}
                  </div>
                )}

                <div className="flex gap-2 pt-2">
                  <Button variant="outline" size="sm" className="flex-1">
                    <Eye className="w-3 h-3 mr-1" />
                    查看
                  </Button>
                  {!agent.isBuiltin && (
                    <>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setEditingAgent(agent.id)}
                      >
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDeleteSubAgent(agent.id)}
                      >
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredAgents.length === 0 && (
        <div className="text-center py-12">
          <p className="text-muted-foreground">没有找到匹配的 sub-agents</p>
        </div>
      )}
    </div>
  );
}

